﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;

namespace AttributeDoem
{
    /// <summary>
    /// 枚举拓展方法
    /// </summary>
    public static class EnumExpand
    {
        /// <summary>
        /// 返回枚举备注
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetEnumRemark(this Enum value)
        {
            //反射类型
            Type type = value.GetType();
            //获取字段
            var field = type.GetField(value.ToString());
            if (field == null)
            {
                throw new Exception("请添加特性");
            }
            //判断字段是否添加RemarkAttribute特性 ，第二个参数可以根据继承链寻找
            if (field.IsDefined(typeof(RemarkAttribute), true))
            {
                //获取RemarkAttribute特性
                RemarkAttribute remarkAttribute = (RemarkAttribute)field.GetCustomAttribute(typeof(RemarkAttribute), true);
                return remarkAttribute.GetRemark();
            }
            else
            {
                throw new Exception("请添加特性");
            }
            throw new Exception("调用错误");
        }

        //根据枚举的int值取出枚举字段
        public static T GetEnunCallFunction<T>(int value) where T : Enum
        {
            T call = (T)Enum.Parse(typeof(T), value.ToString());
            return call;
        }

        /// <summary>
        /// 获取枚举字段Description属性别乱用
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum value)
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            if (fieldInfo.IsDefined(typeof(DescriptionAttribute), true))
            {
                DescriptionAttribute descriptionAttribute = (DescriptionAttribute)fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute), true);
                return descriptionAttribute.Description;
            }
            //程序猿劝退师
            throw new Exception("你写的鸡儿代码Description都不加！！");
        }

        #region 获取枚举集合
        /// <summary>
        /// 获取枚举集合
        /// </summary>
        /// <returns></returns>
        public static Dictionary<int, string> GetEnumDescriptionTypeDictionary<T>() where T : Enum, new()
        {
            Dictionary<int, string> keyValuePairs = new Dictionary<int, string>();
            T enumType = new T();
            //获取所有的字段
            FieldInfo[] fieldInfo = enumType.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);
            foreach (var item in fieldInfo)
            {
                DescriptionAttribute descriptionAttribute = (DescriptionAttribute)item.GetCustomAttribute(typeof(DescriptionAttribute), true);
                keyValuePairs.Add(Convert.ToInt32(item.GetValue(enumType)), descriptionAttribute.Description);
            }
            return keyValuePairs;
        }
        #endregion

    }
}
